import cv2
import imutils
import numpy as np
import os

#模糊逻辑以及最大隶属原则
def Gdt(x,xm,s2):
    if abs(x-xm) <=(2*s2**0.5):
        #return (abs(1-((x-xm)/(2*s2** 0.5))**2))
        #print(((x-xm)/(2*(s2**0.5)))**2)
        B=(x-xm)**2
        A=4*s2
        return(1-(B/A))
    else :
        return 0

#A1是正例
def Ai(Ai1,Ai2,Ai3):
    return (Ai1+Ai2+Ai3)/2

def compare (x,y):
    if x>=y :
        return 1
    else :
        return 0
def contract(binaryimage,grayimage):
    area=len(binaryimage[binaryimage==0])
    gm=cv2.mean(grayimage)[0]
    #对比度计算
    m, n = grayimage.shape
    img1_ext = cv2.copyMakeBorder(grayimage,1,1,1,1,cv2.BORDER_REPLICATE) 
    rows_ext,cols_ext = img1_ext.shape
    
                    
    b = 0.0
    for i in range(1,rows_ext-1):
        for j in range(1,cols_ext-1):
            b += ((img1_ext[i,j]-img1_ext[i,j+1])**2 + (img1_ext[i,j]-img1_ext[i,j-1])**2 + 
                    (img1_ext[i,j]-img1_ext[i+1,j])**2 + (img1_ext[i,j]-img1_ext[i-1,j])**2)

    cg = b/(4*(m-2)*(n-2)+3*(2*(m-2)+2*(n-2))+2*4) #对应上面48的计算公式


    a1=Ai(Gdt(gm,127.8321104,84.31149125),Gdt(area,691.8513514,91809),Gdt(cg,24212.95928,2095307.229))#填涂
    b1=Ai(Gdt(gm,201.265412,78.53247543),Gdt(area,11.1565254,249032.0686),Gdt(cg,16166.92781,598052.5273))#未填涂
    return(a1,b1)


#批量读取
list=[]
length=len(os.listdir("image\\2T"))

#读入图片地址
for i in range(length):
    list.append("image\\2T\{}.jpg".format(str(i+1))) 

#对读入的图片批量操作
#对读入的图片批量操作
A=0
B=0
for j in range(length):
    image=cv2.imread(list[j])
    grayimage = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)#灰度
    _O, binaryimage = cv2.threshold(grayimage, 0, 255, cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)
    A=A+contract (binaryimage,grayimage)[0]
    B=B+contract (binaryimage,grayimage)[1]
    print(j)
g=A/length
h=B/length
i=  (A/length)/(B/length)

print(g,h,i)